package com.example.foo.admin.task;

import java.time.LocalDate;
import java.util.List;

import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.account.AccountHelper;
import com.example.foo.ftt.FttProfitException;
import com.example.foo.ftt.model.FttProfit;
import com.example.foo.ftt.query.FttProfitQuery;
import com.example.foo.ftt.service.FttProfitFacadeService;
import com.example.foo.ftt.service.FttProfitService;
//网体分红-日结算，结算每个等级昨天的盈利，若对应等级人数>0且分红金额>0进行分红，分红状态改为成功;否则，不分红，分红状态改为失败。
@org.springframework.stereotype.Component("fttProfitSettleTask")
public class FttProfitSettleTask {

	private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(getClass());

	private final FttProfitService fttProfitService;
	private final FttProfitFacadeService fttProfitFacadeService;

	public FttProfitSettleTask(FttProfitService fttProfitService,
			FttProfitFacadeService fttProfitFacadeService) {
		this.fttProfitService = fttProfitService;
		this.fttProfitFacadeService = fttProfitFacadeService;
	}

	public void execute(Integer offsetDay) throws Exception {
		Integer periodDay = AccountHelper.toPeriodDay(LocalDate.now().plusDays(offsetDay));

		FttProfitQuery fttProfitQuery = new FttProfitQuery();
		fttProfitQuery.setState(FttProfit.State.pending);
		fttProfitQuery.setPeriodDay(periodDay);

		for (Pageable fttProfitPageable = new Pageable(1, 100); ; ) {
			PageResult<FttProfit> fttProfitPageResult = fttProfitService.findFttProfits(fttProfitQuery, fttProfitPageable);
			List<FttProfit> fttProfits = fttProfitPageResult.getRows();
			if (fttProfits.isEmpty()) {
				break;
			}

			for (FttProfit fttProfit : fttProfits) {
				try {
					fttProfitFacadeService.updateFttProfitSettle(fttProfit.getId());
				} catch (Exception e) {
					throw new FttProfitException(String.format("FttProfit#%s", fttProfit.getId()), e);
				}
			}
		}

		log.info("DONE!");
	}

}
